<template>
  <div id="box">
    <el-button type="primary" icon="el-icon-plus" @click="showDialog"
      >添加</el-button
    >
    <el-dialog
      :title="tmForm.id ? '修改品牌' : '添加品牌'"
      :visible.sync="tradeMarkVisible"
    >
      <el-form :model="tmForm" style="width: 80%" ref="ruleForm" :rules="rules">
        <el-form-item
          label="品牌名称"
          :label-width="formLabelWidth"
          prop="tmName"
        >
          <el-input v-model="tmForm.tmName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="品牌LOGO"
          :label-width="formLabelWidth"
          prop="logoUrl"
        >
          <el-upload
            class="avatar-uploader"
            action="list-api/admin/product/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="tmForm.logoUrl" :src="tmForm.logoUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip" style="color: red">
              只能上传jpg/png文件，且不超过500kb
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="tradeMarkVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrUpdateTradeMark"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <el-table
      border
      style="width: 100%; margin-top: 20px"
      :data="tradeMarkLimit.records"
    >
      <el-table-column
        align="center"
        prop="date"
        label="序号"
        width="180"
        type="index"
      >
      </el-table-column>
      <el-table-column
        align="center"
        prop="tmName"
        label="品牌名称"
        style="width: 50%"
      >
      </el-table-column>
      <el-table-column
        align="center"
        prop="logoUrl"
        label="品牌LOGO"
        style="width: 50%"
        ><template slot-scope="{ row }"
          ><img :src="row.logoUrl" style="width: 100px; height: 100px" />
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="address"
        label="操作"
        style="width: 50%"
        ><template slot-scope="{ row }">
          <el-button type="warning" icon="el-icon-edit" @click="showDialog(row)"
            >修改</el-button
          >
          <el-button type="danger" icon="el-icon-delete" @click="deleteTm(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="margin-top: 20px"
      align="center"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="tradeMarkLimit.current"
      :page-sizes="[5, 10, 20]"
      :page-size="tradeMarkLimit.size"
      layout="  prev, pager, next, jumper,->,sizes,total"
      :total="tradeMarkLimit.total"
    >
    </el-pagination>
  </div>
</template>

<script>
export default {
  name: 'TradeMark',
  data() {
    return {
      // 当前页码
      page: 1,
      // 每页记录数
      limit: 3,
      // 品牌分页数据
      tradeMarkLimit: {},
      // 品牌弹出框是否隐藏
      tradeMarkVisible: false,
      // 弹出框里的字大小
      formLabelWidth: '120px',
      tmForm: {
        tmName: '',
        logoUrl: ''
      },
      // 表单验证
      rules: {
        tmName: [
          { required: true, message: '请输入活动名称', trigger: 'change' },
          {
            min: 2,
            max: 120,
            message: '长度在 2 到 5 个字符',
            trigger: 'change'
          }
        ],
        logoUrl: [{ required: true }, { message: '请选择品牌的图片' }]
      }
    }
  },
  mounted() {
    this.getTradeMarkLimit()
  },
  methods: {
    // 获取品牌分页列表
    async getTradeMarkLimit() {
      const tradeMark = {
        page: this.page,
        limit: this.limit
      }
      const result = await this.$api.tradeMark.reqGetTradeMarkLimit(tradeMark)
      if (result.code === 200) {
        this.tradeMarkLimit = result.data
      } else {
        return Promise.reject(new Error('filer'))
      }
    },
    // 每页显示的页数
    handleSizeChange(limit) {
      this.limit = limit
      this.getTradeMarkLimit()
    },
    // 选择的第几页
    handleCurrentChange(page) {
      this.page = page
      this.getTradeMarkLimit()
    },
    // 显示添加或修改对话框
    showDialog(row) {
      // 显示弹出框
      this.tradeMarkVisible = true
      // 当为修改品牌时，显示修改的品牌
      if (row.id) {
        // 使用浅拷贝，引向同一个地址
        this.tmForm = { ...row }
      } else {
        // 重置弹出框缓存数据
        this.tmForm = {
          tmName: '',
          logoUrl: ''
        }
      }
    },
    // 图片上传成功
    handleAvatarSuccess(res, file) {
      console.log(res)
      // 上传成功
      if (res.code === 200) {
        this.tmForm.logoUrl = res.data
      }
    },
    // 添加或修改品牌
    addOrUpdateTradeMark() {
      // 表单验证
      this.$refs.ruleForm.validate(async(success) => {
        if (success) {
          // 表单验证成功
          // 把对话框隐藏
          this.tradeMarkVisible = false
          // 有值传来时为修改，没有为添加
          const result = await this.$api.tradeMark.reqAddOrUpdateTrademark(
            this.tmForm
          )
          if (result.code === 200) {
            this.$message({
              message: `恭喜你，${this.tmForm.id ? '修改成功' : ' 添加成功'}`,
              type: 'success',
              center: true
            })
            // 表单重置
            this.$refs.ruleForm.resetFields()
            // 成功后，重新请求最新数据
            this.getTradeMarkLimit()
            return 'ok'
          } else {
            return Promise.reject(new Error('filer'))
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
      // // 表单重置
      // this.$refs.ruleForm.resetFields();
    },
    // 图片上传前
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 删除品牌
    deleteTm(row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          // 点击确定删除
          const result = await this.$api.tradeMark.reqDeleteTrademark(row.id)
          if (result.code === 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            // 删除成功后重新刷新页面 原本第几页就在第几页
            this.getTradeMarkLimit()
          } else {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }
  }
}
</script>

<style>
#box {
  margin: 30px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
